package com.example.sqlexample;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DatabaseHelper {
	private SQLiteDatabase mDatabase;
	private static final String DATABASENAME = "database1";
	private static final String TABLENAME = "notes";
	
	public DatabaseHelper(Context context){
		//Open a database with name "database1" that can only be accessed by this application
		mDatabase = context.openOrCreateDatabase(DATABASENAME, Context.MODE_PRIVATE, null);
		//Open a new table called "notes'
		//"notes" only has one column: a string (varchar) called "Note"
		mDatabase.execSQL("CREATE TABLE IF NOT EXISTS " + TABLENAME + " (Note VARCHAR);");
	}
	
	/**
	 * Add a note to the table
	 * @param noteString The note to be added
	 */
	public void addNote(String noteString){
		//Execute SQL that adds a new row
		//where the value of column "Note" is the
		//string passed in
		mDatabase.execSQL("INSERT INTO " + TABLENAME + " (Note)" + " VALUES ('" + noteString + "');");
	}
	
	/**
	 * Deletes the data in the table and creates a new, blank table
	 */
	public void delete(){
		//Drop the table used
		mDatabase.execSQL("DROP TABLE IF EXISTS " + TABLENAME);
		//Then create a new blank table
		mDatabase.execSQL("CREATE TABLE IF NOT EXISTS " + TABLENAME + " (Note VARCHAR);");
	}
	
	/**
	 * @return the notes as an ArrayList of Strings
	 */
	public ArrayList<String> generateNoteList() {
		//Create an ArrayList to hold strings
		ArrayList<String> noteList = new ArrayList<String>();

		Cursor c = mDatabase.rawQuery("SELECT * FROM " + TABLENAME, null);
		int noteColumn = c.getColumnIndex("Note");

		if (c.moveToFirst() && c != null) {
			do {
				noteList.add(c.getString(noteColumn));
			} while (c.moveToNext());
		}

		return noteList;
	}
	
}
